<!--20210312  zaq  修改data中user结构，完善登录方法-->
<!--20210312  zaq  与后端进行登录调试-->
<!--20210318  zaq  修改data中user列，与后端保持一致-->
<!--20210324  zaq  修改登录框布局，暂时注释与后端交互部分，登录成功后弹出导航提示-->
<!--20210421  zaq  修改ruleForm数据格式，新增合法性判断-->
<!--20210502  zaq  解决Missing required prop报错问题，定义loginflag值,修改弹窗信息-->
<!--20210512  zaq  弹窗改为可自动关闭-->
<!--20210513  zaq  修改注册界面，解决注册弹框无反应问题-->
<!--20210517  zaq  与后端进行登录验证调试,完成重置按钮功能-->
<!--20210518  zaq  完成与后端的注册调试,登录成功后返回用户ID-->
<!--20210519  zaq  使用vuex进行数据存放,修改登录登出逻辑-->

<template>
  <div id="window" class="window">
    <div id="login" class="login" >
      <p style="text-align: center;
      font-size: 20px;
      font-style: italic;
      color: white">登录</p>
      <el-form :model="user"  label-width="100px" >
        <el-form-item label="用户名" >
          <el-input style="width: 90%;" v-model="user.uLogin"
                    maxlength="20"
                    show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input style="width: 90%" type="password" v-model="pwd"
                    autocomplete="off"
                    show-password
          ></el-input>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button v-on:click="submitForm(user)">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="text" @click="dialogVisible = true">没有账号？点击注册</el-button>
        </el-form-item>
      </el-form>

      <!--    注册页面-->
      <el-dialog
          title="新用户注册"
          v-model="dialogVisible"
          width="30%"
          :before-close="handleClose">
      <span>
        <el-form :model="registerForm" status-icon
                 label-width="100px"
                 style="text-align: left"
                 :rules="registerRule"
                 ref="registerForm"
        >
          <el-form-item label="用户名:"
                        prop="login"
          >
            <el-input v-model="registerForm.login"
                      maxlength="20"
                      show-word-limit
            ></el-input>
<!--            <span style="color: #fab6b6">注册之后不可修改</span>-->
          </el-form-item>

          <el-form-item label="密码:"
                        prop="pass"
          >
            <el-input style="width: 100%" type="password" v-model="registerForm.pass"
                      autocomplete="off"
                      maxlength="20"
                      show-word-limit
                      show-password
            ></el-input><br>
          </el-form-item>

          <el-form-item label="确认密码:"
                        prop="checkPass"
          >
            <el-input style="width: 100%" type="password" v-model="registerForm.checkPass"
                      autocomplete="off"
                      maxlength="20"
                      show-word-limit
                      show-password
            ></el-input>
            </el-form-item>

          <el-form-item label="用户昵称:"
                        prop="name"
          >
            <el-input v-model="registerForm.name"
                      maxlength="20"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="小星球名字:"
                        prop="planet"
          >
            <el-input v-model="registerForm.planet"
                      maxlength="20"
                      show-word-limit
            ></el-input>
          </el-form-item>
    </el-form>
      </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="register('registerForm')">注册</el-button>
          <el-button @click="resetRegister('registerForm')">重置</el-button>
      </span>
      </el-dialog>

    </div>

<!--    成功信息对话框-->
    <el-dialog
        title="提示"
        v-model="successDialog.visible"
        width="30%"
        :before-close="handleClose">

      <el-result icon="success" title="注册成功" :subTitle="successDialog.message"/>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="successDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="successDialog.visible = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--    失败信息对话框-->
    <el-dialog
        title="提示"
        v-model="failDialog.visible"
        width="30%"
        :before-close="handleClose">

      <el-result icon="error" title="注册失败" :subTitle="failDialog.message"/>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="failDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="failDialog.visible = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { defineComponent ,ref} from 'vue'
import { ElMessage } from 'element-plus'
import {login,register_11101} from '../api/index.js'

export default {
  name: "Login",
  props: {
    loginflag:{
    },
  },
  data() {
    var registerPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var registerPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registerForm.checkPass !== '') {
          this.$refs.registerForm.validateField('checkPass');
        }
        callback();
      }
    };
    var checkName = (rule, value, callback) => {
      //合法性判断
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.signupRuleForm.checkPass !== '') {
          this.$refs.signupRuleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.signupRuleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      // 成功信息
      successDialog:{
        visible:false,
        message:'',
      },
      // 失败信息
      failDialog:{
        visible:false,
        message:'',
      },
      user:{
        code:-1,
        note:'',
        uId:1,//用户id
        uLogin:'',//用户名
        uName:'admin',//用户昵称
        uPwd:'',//密码
        uPlanet:'一颗大傻蛋',//小星球名字
        uCreatedate:'',//用户创建日期
        uBirthday:'',//生日
        uSex:'',//性别
        uStatus:'',//个性签名
        uAdmin:'',//管理员标志
        delete:''//删除标志
      },
      pwd:ref(''),//输入密码
      ruleForm: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur'}
        ],
        name: [
          {validator: checkName, trigger: 'blur'}
        ]
      },
      // 注册表单验证
      registerRule:{
        login:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name:[
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ],
        pass:[
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: registerPass, trigger: 'blur' },
        ],
        checkPass:[
          { validator: registerPass2, trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
        planet:[
          { required: true, message: '请输入小星球名称', trigger: 'blur' },
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ],
      },
      registerForm:{
        login:'',
        name:'',
        pass:'',
        checkPass:'',
        planet:'',
      },
      rules: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        name: [
          {validator: checkName, trigger: 'blur'}
        ]
      },
      dialogVisible: false,
    };
  },
  methods: {
    // 重置注册信息
    resetRegister(registerForm){
      this.$refs[registerForm].resetFields();
    },
    //注册
    register(register){
      const _this=this;
      let user={
        code:-1,
        note:'',
        uId:-1,//用户id
        uLogin:this.registerForm.login,//用户名
        uName:this.registerForm.name,//用户昵称
        uPwd:this.registerForm.pass,//密码
        uPlanet:this.registerForm.planet,//小星球名字
        uCreatedate:1,//用户创建日期
        uBirthday:1,//生日
        uSex:'',//性别
        uStatus:'',//个性签名
        uAdmin:0,//管理员标志
        delete:0//删除标志
      };
      console.log(this.registerForm)
      console.log('注册信息:');
      console.log(user)

      //验证表单合法性
        this.$refs[register].validate((valid) => {
          if (!valid) {
            ElMessage.warning({
              message: '填写信息不符合规范，请重试',
              type: 'warning'
            });
            return false;
          }else {
            //调用11101接口进行用户注册
            register_11101(user).then(resp=>{
              if(resp.code>0){
                //关闭注册框
                _this.dialogVisible=false;

                //弹出成功提示
                _this.successDialog.message=resp.note;
                _this.successDialog.visible=true;

                //清空注册表

              }else{
                //弹出失败信息
                _this.failDialog.message=resp.note;
                _this.failDialog.visible=true;
              }
            }).catch(error => {
              console.log('调用接口11101失败：' + error);
            });
          }
        });

    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    //登录
    submitForm(user) {
      const _this = this;
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      user.uPwd = _this.pwd;

      // // 向父组件App.vue传值，'1'表示成功登录
      // this.$emit('changeLoginFlag','1')

      //用户名密码检查
      login(user).then(resp => {
        user.code = resp.code;
        user.note=resp.note;
        user.uId=resp.uId;
        user.uLogin=resp.uLogin;
        user.uName=resp.uName;
        user.uPwd=resp.uPwd;
        user.uPlanet=resp.uPlanet;
        user.uCreatedate=resp.uCreatedate;
        user.uBirthday=resp.uBirthday;
        user.uSex=resp.uSex;
        user.uStatus=resp.uStatus;
        user.uAdmin=resp.uAdmin;
        console.log('成功' + user.uId);
        console.log('code:'+user.code);
        if(user.code>0){//登录成功
          ElMessage.success({
            message: '登录成功',
            type: 'success'
          });
          this.$emit('changeLoginFlag','1',user);
          if(resp.uAdmin==true){
            sessionStorage.setItem("admin",'1')
          }else{
            sessionStorage.setItem("admin",'0')
          }
          console.log('admin'+sessionStorage.getItem("admin"))
          //成功后弹窗提示
          this.$notify({
            title: '系统信息',
            message: '欢迎使用 一颗小星球 系统',
            // duration: 0
          });
          // this.$notify({
          //   title: '系统信息',
          //   message: '系统尚未完善',
          //   // duration: 0,
          //   offset: 100
          // });
          // this.$notify({
          //   title: '系统信息',
          //   message: '上一次更新时间为2021-6-8',
          //   // duration: 0,
          //   offset: 200
          // });
          _this.user=user;

          //将用户信息放入sessionStorage
          sessionStorage.setItem("uId",user.uId);
          sessionStorage.setItem("uPlanet",user.uPlanet);
          //将用户信息放入vuex
          _this.$store.dispatch("setUId",user.uId);
          _this.$store.dispatch("setUPlanet",user.uPlanet);
          // console.log(_this.$store.state.isLogin)
          // console.log(_this.$store.state.uId)
          // console.log("session:"+sessionStorage.getItem("uId"))


          // 跳转到主页
          this.$router.push('/home')
        }
        else {
          console.log(user.note);
          ElMessage.error('登录失败:'+user.note);
          _this.pwd=ref('');
        }
      }).catch(error => {
        console.log('失败' + error);
      });
      // vue.axios({
      //   method:'post',
      //   url: "http://localhost:9090/user/login",
      //   headers: {
      //     'Content-Type': 'application/json;charset=UTF-8'
      //   },
      //   data: i_user,
      //   // ajax
      //   dataType: "JSON",
      //   type: "post",
      //   // contentType: ‘application/json;charset=UTF-8‘, //不能加
      //   success: function (msg) {
      //     console.log(msg)
      //
      //   }
      // }).then(function (resp){
      //   console.log(resp)
      //   _this.user=resp.data()
      // })
      //     .catch(function (error){
      //       console.log(error)
      //     })

        // }
        //
        // else {
        //   this.$message('????');
        //   console.log('error submit!!');
        //   return false;
        // }
      // });

    },
    resetForm (){
      this.signupRuleForm.name='';
      this.signupRuleForm.pass=ref('');
      this.signupRuleForm.checkPass=ref('');
    },
    signup(formName) {
      let name = '1';
      let pass = '1';
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //用户名密码检查
      if (1) {
        this.$message('输入正确');
        //跳转
        //重新进入登陆页面
        // this.$router.push({
        //   // path: '/main',
        //   name: '/',
        //   params:{
        //     key:'key',
        //     user:{
        //       id:'admin',
        //       name:'章张',
        //       planet:'大傻蛋'
        //     }
        //   }
        // });
      } else {
        this.$message('用户名或密码错误');
      }
      //   } else {
      //     this.$message('????');
      //     console.log('error submit!!');
      //     return false;
      //   }
      // });
    }
  },
  computed:{
    isLogin(){
      //判断是否登录
      var uId=sessionStorage.getItem("uId")
      var uPlanet=sessionStorage.getItem("uPlanet")
      if(uId!=null||uId!=-1||uId!=''||uId!='null'){
        this.$store.commit("userStatus",uId,uPlanet)
        console.log("login页面判断结果已登录,Id:"+uId)
      }else{
        this.$store.commit("userStatus",-1,null)
        console.log("login页面判断结果未登录,Id:"+uId)
      }
      return this.$store.getters.isLogin
    }
  },
}
</script>

<style scoped>
.login {
  width: 500px;
  vertical-align: center;
  /*float:right;*/
  margin: 0;
  padding: 0;
}

.window{
  display: flex;
  /*position: fixed;*/
  right: 0;
  top: 0;
  justify-content: center;
  align-items: center;
  font-size: 0;
}

#login {
  background-color: rgba(0, 0, 0, 0.2);
  width: 500px;
  /*float: bottom;*/
}
</style>